<template>
    <view :style="{height: `${pageHeight}px`}" class="message-container">
        <simpleTopBar @onTap="onTap" @topBarHeight="topBarHeight" :backgroundColor="backgroundColor" :title="contactName" :iconList="iconList"></simpleTopBar>
        <view class="scroll-view">
            <scroll-view ref="scrollViewRef"  @scroll="loadChatMessage" :scroll-top="scrollTop" :scroll-with-animation="true" :scroll-into-view="pageScrollTop" :style="{height: `${scrollHeightView}px`}" scroll-y="true" class="scroll-Y">
                <view v-for="(message, index) in messageList" :key="message"  class="infinite-list-item" :id="'message-'+index">
                    <view v-if="message.sendUserId != userId" class="container">
                        <view class="left">
                            <image v-if="currentSession.contactId != 'Urobot' && currentSession.avatar" 
                            :src="currentSession.avatar" 
                            class="avatar-img"/>
                            <image v-else-if="currentSession.contactId == 'Urobot'" 
                            :src="Robot" 
                            class="avatar-img"/>
                            <view v-else class="avatar-img-no">{{ currentSession.contactName[0] }}</view>
                            <!--消息内容-->
                            <view class="chat-bubble receiver" v-html="message.messageContent"></view>
                        </view>
                    </view>
                    <view v-else class="container">
                        <view class="right">
                            <view class="chat-bubble sender" v-html="message.messageContent"></view>
                            <image v-if="userStore.userAvatar" :src="userStore.userAvatar" class="avatar-img"/>
                            <view v-else class="avatar-img-no">{{ userStore.nickName[0] }}</view>
                        </view>
                    </view>
                </view>
            </scroll-view>
            <view class="bottom-container">
                <view class="input-container">
                    <input
                        v-model="inputText"
                        @input="inputTextChange"
                        class="input-text"
                    />
                    <button
                        :disabled="inputText.length === 0"
                        type="primary"
                        class="send-btn"
                        @tap="sendMessageClick"
                    >  发送
                    </button>
                </view>
                <!--底部图标-->
                <view class="icon-container">
                    <uni-icons type="mic" size="30" />
                    <uni-icons type="phone" size="30" />
                    <uni-icons type="image" size="30" />
                    <uni-icons type="camera" size="30" />
                    <uni-icons type="heart" size="28" />
                    <uni-icons type="more" size="30" />
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import {ref, onMounted, onUnmounted} from 'vue';
import {onLoad} from '@dcloudio/uni-app';
import simpleTopBar from '../../components/simple_top_bar.vue';
import { readClean, updateSessionMessage } from '../../db/ChatSessionUserModel';
import { selectCurrentMessage, saveMessage, selectMessageList } from '../../db/ChatMessageModel';
import { sendMessage, robotReply } from '../../api/message';
import { useSessionListStore } from '../../store/sessionList';
import { useUserInfoStore } from '../../store/user';
import  { addWsListener, removeWsListener} from '../../ws/wsClient'
import { currentSessionStore } from '../../store/session';
import Robot from '../../static/login/robot.jpg';

const currentSession = currentSessionStore().getSession
//消息列表
const messageList = ref([])
//页面滚动条位置
const pageScrollTop = ref('')
const scrollTimeTop = ref(0)
const scrollTop = ref(0)
const scrollViewRef = ref(null)
//ws接收消息
const isStreamMessage = ref(0)
const receiveMessage = () => {
    //注册ws监听
    addWsListener('reciveNewMessage', (data) => {
        //判断是否是AI消息
        if(data.contactId == 'Urobot'){
            //判断是否是当前会话
            if(isStreamMessage.value == 0){
                isStreamMessage.value = isStreamMessage.value + 1
                messageList.value.push(data)
                scrollTop.value = scrollTimeTop.value
                return;
            }
            if(data.sessionId == currentSession.sessionId && data.messageType == 13){
                let count = messageList.value.length - 1
                messageList.value[count].messageContent = messageList.value[count].messageContent + data.messageContent
                //实时滚动到底部
                scrollTop.value = scrollTop.value + 50
            }else{
                isStreamMessage.value = 0
                scrollToBottom()
            }
        }else{
            //判断是否是当前会话
            messageList.value.push(data)
            //滚动到底部
            scrollToBottom()
        }
       
    }) 
}

//会话store
const sessionListStore = useSessionListStore()
//用户store
const userStore = useUserInfoStore().getUser

//传到子组件的标题和图标
const contactName = ref('')
const sessionId = ref('')
const contactId = ref('')
const userId = ref('')
const contactType = ref('')
const iconList = ref([])
const backgroundColor = ref('#f5f5f5')
//获取页面的高度
const pageHeight = ref(0)
const scrollHeightView = ref(0)
const getPageHeight = () => {
    const systemInfo = uni.getSystemInfoSync()
    pageHeight.value = systemInfo.screenHeight-80
    console.log("页面高度", systemInfo.screenHeight)
    console.log("屏幕高度", systemInfo.windowHeight)

}
//获取子组件的高度
const topBarHeight = (height) => {
    scrollHeightView.value = pageHeight.value - height - 35
}
//从数据库查询聊天信息
const getChatMessage = async () => {
    //将未读改为已读
    await readClean(contactId.value)
    //从数据库获取聊天信息
    const result =await selectCurrentMessage(sessionId.value)
    messageList.value = result
    isStreamMessage.value = false
    // 设置页面滚动条位置
    scrollToBottom()
    console.log("获取聊天信息成功", result, userStore)

}
//输入框内容
const inputText = ref('')

const inputTextChange = (e) => {
    // console.log("输入框内容", e)

}
//发送消息
const sendMessageClick = async () => {
    //判断是否给机器人发送发消息
    console.log("发送消息", contactId.value)
    if(contactId.value == 'Urobot'){
        let res = await robotReply({
            messageContent: inputText.value,
            contactId: contactId.value,
            messageType: 2,
            contactType: contactType.value
        })
        if(res && res.code == 0){
            console.log("发送成功", res)
            let data = res.result
            //清空输入框
            inputText.value = ''
            //将消息储存到本地
            await saveMessage(data)
            //更新session
            data.lastReceiveTime = data.sendTime;
            updateSessionMessage(sessionId.value, data)
            //更新聊天信息
            updateMessage(data)
        }
    }else{
        //发送消息到后端
        let res = await sendMessage({
            messageContent: inputText.value,
            contactId: contactId.value,
            messageType: 2,
            contactType: contactType.value
        })
        if(res && res.code == 0){
            console.log("发送成功", res)
            let data = res.result
            //清空输入框
            inputText.value = ''
            //将消息储存到本地
            await saveMessage(data)
            //更新session
            data.lastReceiveTime = data.sendTime;
            updateSessionMessage(sessionId.value, data)
            //更新聊天信息
            updateMessage(data)
        }
    }
    
}
//更新聊天信息
const updateMessage = (message) => {
    messageList.value.push(message)
    //更新sessionList
    sessionListStore.updateSession(message)
    //滚动到底部
    scrollToBottom()
}

//滚动到底部
const scrollToBottom = () => {
    pageScrollTop.value = 'message-'+ (messageList.value.length - 1)
}

//上翻查询聊天历史
const messageCountInfo = {
    totalPage: 0,
    pageNo: 0,
    maxMessageId: null,
    noData: false
}
const lock = ref(true)
const loadChatMessage = async (event) => {
    // 获取 scroll-view 的高度和当前滚动位置
    const { scrollTop, deltaY, scrollHeight } = event.detail;
    scrollTimeTop.value = scrollTop
    //判断是否向上滑动
    if(scrollTop < (scrollHeightView.value/2) && deltaY > 0 && lock.value){
        
        lock.value = false;
        //初始化数据
        messageCountInfo.maxMessageId = messageList.value.length > 0 ? messageList.value[0].messageId : null;
        console.log("上翻查询聊天历史", messageCountInfo)
        if(messageCountInfo.noData) {
            return;
        }
        messageCountInfo.pageNo++;
        const result = await selectMessageList({
            sessionId: sessionId.value,
            pageNo: messageCountInfo.pageNo,
            maxMessageId: messageCountInfo.maxMessageId,
        })
        //在messageList的开始位置中添加数据
        messageList.value = result.dataList.concat(messageList.value)
        //如果没有数据，则设置noData为true  
        if(result.dataList.length == 0) {
            messageCountInfo.noData = true;
        }
        //更新maxMessageId
        if(result.dataList.length > 0){
            messageCountInfo.maxMessageId = result.dataList[0].messageId
        }
        lock.value = true;
    } 
    
}
//获取页面左上方icon
const onTap = (item) => {
    if(item == 'phone'){
        console.log("点击电话")
        //跳转到拨号界面
        uni.navigateTo({
            url:'/pages/index/video_call',
        })
    }else if (item == 'bars'){
        console.log("点击菜单")
    }
}
onMounted(() => {
    getPageHeight()
    getChatMessage()
    receiveMessage()
})
onUnmounted(() => {
    //移除监听器
    removeWsListener('reciveNewMessage')
})
onLoad((option) => {
    //获取传过来的参数
    userId.value = option.userId
    contactName.value = option.contactName
    sessionId.value = option.sessionId
    contactId.value = option.contactId
    contactType.value = option.contactType
    iconList.value = ["phone","bars"]
})
</script>

<style lang="scss" scoped>
.scroll-view{
    height: 100%;
    display: flex;
    flex-direction: column;
    flex: 1;
    .scroll-Y{
        height: 100%;
        padding: 0 10rpx;
        .infinite-list-item {
            display: flex;
            padding-right: 10rpx;
            flex-direction: column;
            font-size: 28rpx;
            .container{
                display: flex;
                width: 100%;
                .left{
                    width: 100%;
                    display: flex;
                }
                .right{
                    display: flex;
                    width: 100%;
                    justify-content: flex-end;
                }
                .avatar-img {
                    width: 80rpx; /* 头像宽度 */
                    height: 80rpx; /* 头像高度 */
                    border-radius: 50%; /* 圆形 */
                    margin-top: 5px;
                    margin-right: 8px; /* 头像和气泡之间的间距 */
                }
                .avatar-img-no{
                    width: 80rpx; /* 头像宽度 */
                    height: 80rpx; /* 头像高度 */
                    border-radius: 50%; /* 圆形 */
                    margin-top: 5px;
                    margin-right: 8px; /* 头像和气泡之间的间距 */
                    font-size: 30rpx;
                    background-color: #c1c1c1;
                    text-align: center;
                    line-height: 80rpx;
                }
            }
            .chat-bubble {
                max-width: 60%; /* 最大宽度 */
                padding: 10px 15px; /* 内边距 */
                border-radius: 5px; /* 圆角边框 */
                margin: 10px 3px; /* 外边距 */
                position: relative; /* 相对定位 */
                word-wrap: break-word; /* 自动换行 */
                display: flex; /* 使用 Flexbox */
                align-items: center; /* 垂直居中对齐 */
            }
            .sender {
                background-color: #ddeffb; /* 发送者气泡颜色 */
                align-self: flex-end; /* 发送者对齐 */
                margin-right: 13px;
            }

            .receiver {
                background-color: #efefef; /* 接收者气泡颜色 */
                align-self: flex-start; /* 接收者对齐 */
            }
            .sender::after, .receiver::after {
                content: '';
                position: absolute;
                width: 0;
                height: 0;
            }

            .sender::after {
                left: 100%; /* 箭头位置 */
                top: 10px; /* 箭头垂直位置 */
                border-left: 10px solid #ddeffb; /* 箭头颜色 */
                border-top: 5px solid transparent; /* 箭头透明部分 */
                border-bottom: 5px solid transparent; /* 箭头透明部分 */
            }

            .receiver::after {
                right: 100%; /* 箭头位置 */
                top: 10px; /* 箭头垂直位置 */
                border-right: 10px solid #efefef; /* 箭头颜色 */
                border-top: 5px solid transparent; /* 箭头透明部分 */
                border-bottom: 5px solid transparent; /* 箭头透明部分 */
            }
        }
        
    }
}
.bottom-container{
    .input-container{
        display: flex;
        padding: 10rpx 20rpx;
        .input-text{
            height: 35px;
            width: 70%;
            border: none;
            background-color: #ffffff;
            border-radius: 10rpx;
            padding-left: 20rpx;
            caret-color: #58a9fd;
        }
       .send-btn{
            flex: 1;
            margin-left: 20rpx;
            font-size: 30rpx;
            height: 35px;
            text-align: center;
            line-height: 35px;
            border: none;
       }
    }
    .icon-container{
        display: flex;
        padding: 0 20rpx;
        align-items: center;
        justify-content: space-between;
    }
    flex: 1;
    background-color: #ddeffb;
    
}


</style>